var dataArray=[];
var dataTable=null;
var nEditing = null;
var nRow;
var rowList = [];
jQuery(document).ready(function() {
	
	
	
	
	//提示信息初始设置
	toastr.options = {
			  "closeButton": true,
			  "debug": false,
			  "positionClass": "toast-top-center",
			  "onclick": null,
			  "showDuration": "1000",
			  "hideDuration": "1000",
			  "timeOut": "5000",
			  "extendedTimeOut": "1000",
			  "showEasing": "swing",
			  "hideEasing": "linear",
			  "showMethod": "fadeIn",
			  "hideMethod": "fadeOut"
			};
	
	
	//点击分配任务
	$("#fenpei_btn").click(function(){
		var selectNum =$('#edit_plan_table').find(".active").length;
		if(selectNum>0){
			$("#fenpeiEmployee").modal();
		}else{
			toastr.error("请选择一条记录","系统提示");
		}	
	});
	
	var planUnitSelect2 = $("#planUnit").select2({
	    placeholder: "请选择客户单位名称",
	    //minimumInputLength: 1,//加了这个不展示全部下拉选项了
	    allowClear: true
	});
	var deparmentNameSelect2 = $("#deparmentName").select2({
	    placeholder: "请选择客户部门",
	    allowClear: true
	});
	var contactsNameSelect2 = $("#contactsName").select2({
		placeholder:"请选择客户使用人",
	    allowClear: true
	    //minimumInputLength: 1
	});
	
	var employeeNameSelect2 = $("#employeeName").select2({
	    placeholder: "请选择操作人",
	    //minimumInputLength: 1,
	    allowClear: true
	});
	
	//客户绑定事件
	$("#planUnit").on('change',function(e){
		$("#deparmentName").select2('val','');
		postInitCustomerDepartmentSelect2('web/findDeparmentListByCustomerId.htm',$("#planUnit").select2("val"),'deparmentName');
	});
	
	//客户部门绑定事件
	$("#deparmentName").on('change',function(e){
		$("#contactsName").select2('val','');
		postInitCustomerDepartmentSelect2('web/findContactsListByDepId.htm',$("#deparmentName").select2("val"),'contactsName');
	});
	
	//更改
	$('#edit_plan_table a.edit').live('click', function (e) {
		nRow = $(this).parents('tr')[0];
		var row = dataTable.fnGetData(nRow);
		$("#orderDate").val(row.orderDate);
		$("#goodsName").val(row.goodsName);
		$("#goodsType").val(row.goodsType);
		$("#goodsUnit").val(row.goodsUnit);
		$("#goodsNum").val(row.goodsNum);
		
		//清空操作
		$("#planUnit").select2('val','');
		$("#deparmentName").select2('val','');
		$("#contactsName").select2('val','');
		
		var opt;
		var i =0;
		//设置客户
		var planData = $("#planUnit").select2()[0];
		for(i =0;i<planData.length;i++){
			opt = planData[i];
			if(opt.innerText==row.planUnit){
				$("#planUnit").select2('val',opt.value);
				//读取部门并init
				postInitCustomerDepartmentSelect2('web/findDeparmentListByCustomerId.htm',opt.value,'deparmentName');
				break;
			}
		}
		//设置部门
		var depData = $("#deparmentName").select2()[0];
		for(i = 0;i<depData.length;i++){
			opt = depData[i];
			if(opt.innerText==row.deparmentName){
				$("#deparmentName").select2('val',opt.value);
				//读取客户联系人并init
				postInitCustomerDepartmentSelect2('web/findContactsListByDepId.htm',opt.value,'contactsName');
				break;
			}
		}
		//设置客户联系人
		var contacts = $("#contactsName").select2()[0];
		for(i=0;i<contacts.length;i++){
			opt = contacts[i];
			if(opt.innerText==row.contactsName){
				$("#contactsName").select2('val',opt.value);
				break;
			}
		}
		
		$("#editPlanModal").modal();
	});
	
	//提交单项更改
	$("#btn_commit_one_form").click(function(){
		if($.trim($("#orderDate").val())==''){
			toastr.error("订单时间不能为空！");
			return false;
		}
		if($.trim($("#goodsName").val())==''||$("#goodsName").val()=='NULL'){
			toastr.error("商品名称不能为空！");
			return false;
		}
		if($.trim($("#goodsType").val())==''||$("#goodsType").val()=='NULL'){
			toastr.error("商品规格不能为空！");
			return false;
		}
		if($.trim($("#goodsUnit") .val())==''){
			toastr.error("商品单位不能为空！");
			return false;
		}
		if($.trim($("#goodsNum").val())==''){
			toastr.error("商品数量不能为空！");
			return false;
		}
		if($("#planUnit").val()==''){
			toastr.error("客户单位不能为空！");
			return false;
		}
		if($("#deparmentName").val()==''){
			toastr.error("客户部门不能为空！");
			return false;
		}
		if($("#contactsName").val()==''){
			toastr.error("客户使用人不能为空！");
			return false;
		}
		/*if($.trim($("#employeeName").val())==-1){
			toastr.error("请选择操作人！");
			return false;
		}*/
		/*$.ajax({
    		url:'web/updatePwd.htm',
    		data:$("#one_form").serialize(),
    		type:'post',
    		success:function(data){
    			if(data.success){
    				//$("#btn_commit_one_form").attr("data-dismiss","modal");
    				$("#btn_close_one_form").click();
    			}
    		}
    	});*/
		var aa,bb,cc;
		aa = $("#planUnit").select2('data');
		if(aa==null){
			toastr.error("客户单位不能为空！");
			return false;
		}
		bb =$("#deparmentName").select2('data');
		if(bb==null){
			toastr.error("客户部门不能为空！");
			return false;
		}
		cc = $("#contactsName").select2('data');
		if(cc==null){
			toastr.error("客户使用人不能为空！");
			return false;
		}
		
		dataTable.fnUpdate($.trim($("#orderDate").val()), nRow, 0, false);
		dataTable.fnUpdate($.trim($("#goodsName").val()), nRow, 1, false);
		dataTable.fnUpdate($.trim($("#goodsType").val()), nRow, 2, false);
		dataTable.fnUpdate($.trim($("#goodsUnit").val()), nRow, 3, false);
		dataTable.fnUpdate($.trim($("#goodsNum").val()), nRow, 4, false);
		var a =aa.text;
		var b = bb.text;
		var c = cc.text;
		dataTable.fnUpdate(a, nRow, 5, false);
		dataTable.fnUpdate(b, nRow, 6, false);
		dataTable.fnUpdate(c, nRow, 7, false);
		//console.log($("#employeeName").val());
		//dataTable.fnUpdate($("#employeeName option:selected").text(), nRow, 8, false);
		dataTable.fnUpdate($("#planUnit").select2('val'), nRow, 10, false);
		dataTable.fnUpdate($("#deparmentName").select2('val'), nRow, 11, false);
		dataTable.fnUpdate($("#contactsName").select2('val'), nRow, 12, false);
	});
	
	//确认分配
	$("#btn_fenpei_commitBtn").click(function(){
		if($("#employeeName").val()==-1){
			toastr.error("请务必分配任务！");
			return false;
		}
		for(var i =0;i<rowList.length;i++){
			dataTable.fnUpdate($("#employeeName").select2('data').text, rowList[i], 8, false);
			//console.log($("#employeeName").val());
			dataTable.fnUpdate($("#employeeName").select2('val'), rowList[i], 13, false);
		}
	});
	
	//保存，验证后
	$("#btn_commit").click(function(){
		//开始验证
		var obj;
		var isCheck =true;
		var datas = dataTable.fnGetData();
		var line = 0;
		for(var i=0;i<datas.length;i++){
			line = i+1;
			obj=datas[i];
			if(obj.orderDate==''){
				toastr.error("第"+line+"行订单时间为空！");
				isCheck = false;
			}
			if(obj.goodsName == 'null'||obj.goodsName == 'NULL'){
				toastr.error("第"+line+"行商品名称为空！");
				isCheck = false;
			}
			if(obj.goodsType == 'null'||obj.goodsType == 'NULL'){
				toastr.error("第"+line+"行商品规格为空！");
				isCheck = false;
			}
			if(obj.goodsUnit == 'null'||obj.goodsUnit == 'NULL'||obj.goodsUnit == '' ){
				toastr.error("第"+line+"行商品单位为空！");
			}
			if(obj.goodsNum==''||obj.goodsNum=='NULL'||obj.goodsNum=='null'){
				toastr.error("第"+line+"行商品数量为空！");
				isCheck = false;
			}
			if(obj.planUnit==''||obj.planUnit=='NULL'||obj.planUnit=='null'){
				toastr.error("第"+line+"行客户单位为空！");
				isCheck = false;
			}
			if(obj.deparmentName==''||obj.deparmentName=='NULL'||obj.deparmentName=='null'){
				toastr.error("第"+line+"行客户部门为空！");
				isCheck = false;
			}
			if(obj.contactsName==''||obj.contactsName=='NULL'||obj.contactsName=='null'){
				toastr.error("第"+line+"行客户使用人为空！");
				isCheck = false;
			}
			if(obj.employeeName==''||obj.employeeName=='NULL'||obj.employeeName=='null'||obj.employeeName==null){
				toastr.error("第"+line+"行操作人为空！");
				isCheck = false;
			}
			
			
		} 
		console.log(datas);
		if(isCheck){
			//toastr.success("可以提交！");
			$.ajax({
	    		url:'web/insertPlan.htm',
	    		data:{planListStr:JSON.stringify(datas)},
	    		type:'post',
	    		success:function(data){
	    			if(data.success){
	    				//$("#btn_commit_one_form").attr("data-dismiss","modal");
	    				$("#btn_close_one_form").click();
	    			}
	    		}
	    	});
		}
	});
	
}); 


function showDataTable(){
	if (!jQuery().dataTable) {
        return;
    }

    // begin first table
	dataTable= $('#edit_plan_table').dataTable({
		"sDom" : "<'row'<'col-md-6 col-sm-12'l><'col-md-12 col-sm-12'f>r>t<'row'<'col-md-5 col-sm-12'i><'col-md-7 col-sm-12'p>>", //default layout without horizontal scroll(remove this setting to enable horizontal scroll for the table)
		"sAjaxSource":"web/showTableDataExcelHandler.htm",
		"fnServerData": function ( sSource, aoData, fnCallback ) {
			//aoData.push({name:"rs",value:JSON.stringify(data)});
			$.ajax({
				"dataType":'json',
				"type": "POST",
				"url": sSource,
				"data": aoData,
				"success": fnCallback
			});
		},
        "aoColumns": [
          { "bSortable": false },
          null,
          { "bSortable": false },
          null,
          { "bSortable": false },
          { "bSortable": false }
        ],
        "aLengthMenu": [
            [5, 15, 20, -1],
            [5, 15, 20, "All"] // change per page values here
        ],
        // set the initial value
        "bInfo": true,//页脚信息
		"bFilter":false,
		"bLengthChange":false,//取消显示每页条数
		"bProcessing": false,//开关，以指定当正在处理数据的时候，是否显示“正在处理”这个提示信息
		"bPaginate": false,//开关，是否显示（使用）分页器
		"bServerSide": false,//true依据后台排序
		"bStateSave": false,//状态保存，使用了翻页或者改变了每页显示数据数量，会保存在cookie中
		"bJQueryUI":false,//是否用jquery样式
		"sZeroRecords": "没有检索到数据",
        "iDisplayLength": 5,
        "sPaginationType": "bootstrap",
        "oLanguage": {
            "sLengthMenu": "_MENU_ records",
            "oPaginate": {
                "sPrevious": "Prev",
                "sNext": "Next"
            }
        },
        
        //'bSortCellsTop': true,
        "aoColumns": [
                      /*{ "bSortable": false,"sClass": "center",
                    	  "mRender":function(data,type,full){
                          	return '<input type="checkbox" class="checkboxes" value="'+data+'" />';
                          }
                      },*/
		              { 'mDataProp':'orderDate',"bSortable": false,"sClass": "center","sTitle":"订单时间"},
		              { 'mDataProp':'goodsName',"bSortable": false,"sClass": "center","sTitle":"商品名称",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'goodsType',"bSortable": false,"sClass": "center","sTitle":"商品规格",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'goodsUnit',"bSortable": false ,"sClass": "center","sTitle":"商品单位",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'goodsNum',"bSortable": false ,"sClass": "center","sTitle":"商品数量",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  console.log(data);
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'planUnit',"bSortable": false,"sClass": "center","sTitle":"客户单位",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  } 
		              },
		              { 'mDataProp':'deparmentName',"bSortable": false,"sClass": "center","sTitle":"客户部门",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'contactsName',"bSortable": false,"sClass": "center","sTitle":"客户使用人",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'employeeName',"bSortable": false,"sClass": "center","sTitle":"操作人",
		            	  "mRender": function ( data, type, row ) {
		            		  if(data==undefined||data==''||data=='NULL'){
		            			  return '<span style="color:red;">未填写</span>';
		            		  }else{
		            			return data;
		            		  }
		            	  }
		              },
		              { 'mDataProp':'bak',"bSortable": false,"sClass": "center","sTitle":"操作",
		            	  "mRender": function ( data, type, row ) {
		            		//return '<span><a class="edit btn btn-xs blue" href="javascript:editPlanFun(\''+row+'\')">更改</a></span>';
		            		return '<span><a class="edit btn btn-xs blue" href="javascript:void(0);">更改</a></span>';
		            		//+'<span><a class="btn btn-xs dark" href="javascript:;">保存</a></span>';
		            		//+'<span><a class="btn btn-xs green" href="javascript:addContacts(\''+data+'\');">添加联系人</a></span>';
		            	  }
		              },
		              { 'mDataProp':'customerId',"bSortable": false,"sClass": "center hidden","sTitle":"customerId"},
                      { 'mDataProp':'depId',"bSortable": false,"sClass": "center hidden","sTitle":"depId"},
                      { 'mDataProp':'contactsId',"bSortable": false,"sClass": "center hidden","sTitle":"contactsId"},
                      { 'mDataProp':'empId',"bSortable": false,"sClass": "center hidden","sTitle":"empId"}
		              ],
		              "bRetrieve": true, 
		              "iDisplayLength": 15,
		              "sPaginationType": "bootstrap",
		              "oLanguage": {
		            	  "sProcessing": '<i class="fa fa-coffee"></i>&nbsp;正在加载中......',
		            	  "sEmptyTable" : "没有查询到数据",
		            	  "sLengthMenu": "每页展示    _MENU_  条 ",
		            	  "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
		            	  "sInfoEmpty":"当前显示0到0条，共0条记录",
		            	  "oPaginate": {
		            		  "sFirst": "首页",
		            		  "sPrevious": "上一页 ",
		            		  "sNext": "下一页",
		            		  "sLast": "末页",
		            	  }
		              },
		              "aoColumnDefs": [//指定可排序的列
		              {
		                  'bSortable': false,
		                  'aTargets': [0]
		              }
		          ],
	              "fnInitComplete": function() {
	                  this.fnAdjustColumnSizing(true);
	              },
	              "fnCreatedRow": function( nRow, aData, iDisplayIndex ) {
	                  $(nRow).on('click', function (){//行click击事件
	                  	if($(this).hasClass("active")){
	                  		$(this).removeClass("active");
	                  		for(var i=0;i<dataArray.length;i++){
            				  if(dataArray[i].id==aData.id){
            					  dataArray.splice(i,1);
            				  }
            				  if(rowList[i].id==aData.id){
            					  rowList.splice(i,1);
            				  }
            			  	}
	                  	}else{
	                  		//$('#add_plan_table tbody tr').removeClass("active");
	                  		var set = jQuery(this).attr("data-set");
	                  		$(this).toggleClass("active");
	                  		jQuery.uniform.update(set);
	                  		dataArray.push(aData);
	                  		rowList.push(nRow);
	                  	}
	                  	if(dataArray.length>0){
	                  		$("#fenpei_btn").removeClass("disabled");
	                  	}else{
	                  		$("#fenpei_btn").addClass("disabled");
	                  	}
	                  	//console.log(dataArray.length);
	                  });
	              }
    });
	
	/*jQuery('#edit_plan_table .group-checkable').change(function () {
        var set = jQuery(this).attr("data-set");
        var checked = jQuery(this).is(":checked");
        jQuery(set).each(function () {
            if (checked) {
                $(this).attr("checked", true);
            } else {
                $(this).attr("checked", false);
            }
            $(this).parents('tr').toggleClass("active");
        });
        jQuery.uniform.update(set);

    });

    jQuery('#edit_plan_table tbody tr .checkboxes').change(function(){
         $(this).parents('tr').toggleClass("active");
         jQuery.uniform.update(set);
    });*/

    //jQuery('#edit_plan_table_wrapper .dataTables_filter input').addClass("form-control input-medium"); // modify table search input
    //jQuery('#edit_plan_table_wrapper .dataTables_length select').addClass("form-control input-xsmall"); // modify table per page dropdown

}

/**
 * 公用方法，
 * 实现select2联动填充；
 */
//'web/findDeparmentListByCustomerId.htm',$("#planUnit").select2("val"),'deparmentName'
function postInitCustomerDepartmentSelect2(url,idValue,selector){
	$.ajax({
		type:'post',
		async:false,
		url:url,
		data:{
			selectId:idValue
		},
		success:function(data){
			if(data.success){
				$("#"+selector).empty();
				var d = data.aaData;
				//$("#deparmentName").select2({data:d});
				var option;
				$.each(d , function(index , obj) {
					option	= '<option value="'+obj.id+'">'+obj.text+'</option>';
					$("#"+selector).append(option);
				})
			}
		},
		dataType:'json'
	});
}

/**
 * 保存row data
 */
function saveRow(oTable, nRow) {
	
	$("#orderDate").val(row.orderDate);
	$("#goodsName").val(row.goodsName);
	$("#goodsType").val(row.goodsType);
	$("#goodsUnit").val(row.goodsUnit);
	$("#goodsNum").val(row.goodsNum);
	$("#planUnit").val(row.planUnit);
	$("#deparmentName").val(row.deparmentName);
	$("#contactsName").val(row.contactsName);
}